﻿#include "TextBlock.h"
#include <QFontMetrics>
#include <QDebug>

namespace Qly
{
TextBlock::TextBlock()
{
    m_boundingRect.setRect(0, 0, 0, 0);
}

TextBlock::~TextBlock()
{

}

void TextBlock::setBottomCenter(QPoint p)
{
    int width = m_boundingRect.width();
    int height = m_boundingRect.height();
    moveTo(p.x() - width / 2.0, p.y() - height - 5);
}

void TextBlock::setTopCenter(QPoint p)
{
    int width = m_boundingRect.width();
    moveTo(p.x() - width / 2.0, p.y() - 1);
}

void TextBlock::moveTo(int x, int y)
{
    int detX = x - m_boundingRect.left();
    int detY = y - m_boundingRect.top();
    m_boundingRect.moveTo(x, y);
    QList<QRect>::iterator i;
    for (i = m_textsRect.begin(); i != m_textsRect.end(); ++i)
    {
        i->translate(detX, detY);
    }
}

void TextBlock::moveTo(QPoint p)
{
    moveTo(p.x(), p.y());
}

void TextBlock::setTextList(QStringList texts)
{
    m_texts = texts;
    updateBoundingRect();
}

void TextBlock::updateBoundingRect()
{
    //qDebug() << m_font;
    m_textsRect.clear();
    int width = 0, height = 0;
    int offsetX = m_boundingRect.left();
    int offsetY = m_boundingRect.top();
    QFontMetrics fm(m_font);
    QStringListIterator i(m_texts);
    while(i.hasNext())
    {
        QRect br = fm.boundingRect(i.next());
        br.moveTo(offsetX, offsetY + height);
        //qDebug() << "updateBoundingRect: m_textsRect" << br;
        m_textsRect.push_back(br);
        height += br.height();
        if(br.width() > width)
        {
            width = br.width();
        }
    }
    m_boundingRect.setWidth(width);
    m_boundingRect.setHeight(height);
    //qDebug() << "updateBoundingRect: m_boundingRect" << m_boundingRect;
}

void TextBlock::setFont(const QFont &font)
{
    m_font = font;
    updateBoundingRect();
}

void TextBlock::setText(QString text)
{
    m_texts = text.split(",");
   // qDebug() << m_texts;
    updateBoundingRect();
}

void TextBlock::translate(QPoint offset)
{
    m_boundingRect.translate(offset);
    QList<QRect>::iterator i;
    for (i = m_textsRect.begin(); i != m_textsRect.end(); ++i)
    {
        i->translate(offset);
       // qDebug() << "translate: m_textsRect" << *i;
    }
   // qDebug() << "translate: m_boundingRect" << m_boundingRect;
}

void TextBlock::draw(QPainter &p)
{
    p.save();
    p.setPen(m_pen);
    p.setFont(m_font);
    QStringListIterator i(m_texts);
    QListIterator<QRect> j(m_textsRect);
    while(i.hasNext() && j.hasNext())
    {
        QRect rect = j.next();
        //qDebug() << "TextBlock::draw rect = " << rect;
        p.drawText(rect, Qt::AlignLeft, i.next());
    }
    p.restore();
}
} //namespace Qly
